const { app, BrowserWindow, ipcMain, Menu, dialog } = require('electron')
const fs = require('fs-extra')
const path = require('path')
const { exec } = require('child_process')
const os = require('os')
const { findGameLog } = require('./utils/detectGame');
// 确保唯一实例
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  app.quit()
}

// 全局变量
let win = null
let logWatcher = null
let logPath = ''
let lastPosition = 0
const isDev = process.env.WEBPACK_DEV_SERVER_URL ? true : false

// 错误日志记录函数
function logError(message, error) {
  const logDir = path.join(os.homedir(), '.wtz-logs')
  const logFile = path.join(logDir, 'error.log')

  try {
    fs.ensureDirSync(logDir)
    const logContent = `[${new Date().toISOString()}] ${message}\n${error ? error.stack || error.message : ''}\n\n`
    fs.appendFileSync(logFile, logContent)
  } catch (err) {
    console.error('日志记录失败:', err)
  }
}

// 显示错误对话框（生产模式）
function showErrorDialog(title, message) {
  if (!isDev && dialog && win) {
    dialog.showErrorBox(title, message)
  }
  console.error(`${title}: ${message}`)
  logError(title, message)
}

// 显示错误页面
function showErrorPage(message) {
  if (win && !win.isDestroyed()) {
    win.loadURL(`data:text/html,<html>
      <head>
        <meta charset="UTF-8">
        <title>加载错误</title>
        <style>
          body { font-family: Arial, sans-serif; padding: 20px; color: #333; }
          h1 { color: #e74c3c; }
          .info { margin-top: 20px; padding: 10px; background: #f5f5f5; }
        </style>
      </head>
      <body>
        <h1>应用加载失败</h1>
        <p>${message}</p>
        <div class="info">
          <p>错误日志已保存至: ${path.join(os.homedir(), '.wtz-logs', 'error.log')}</p>
        </div>
      </body>
    </html>`)
    win.show()
  }
}

// 调用Python脚本获取日志路径
async function autoDetectGameWindow() {
  return new Promise((resolve) => {
    try {
      console.log('开始自动检测游戏...');
      
      // 直接调用函数
      const logPath = findGameLog();
      
      if (logPath) {
        console.log('找到游戏日志路径:', logPath);
        resolve(logPath);
      } else {
        console.log('未找到游戏日志路径');
        resolve(null);
      }
      
    } catch (error) {
      console.error('自动检测失败:', error);
      resolve(null);
    }
  });
}

// 添加路径检测辅助函数
function getPythonPaths() {
  if (!app.isPackaged) {
    return {
      pythonExe: path.join(__dirname, '../python_env', 'Scripts', 'python.exe'),
      script: path.join(__dirname, '../detect_game.py'),
      envDir: path.join(__dirname, '../python_env')
    };
  }

  // 生产模式：尝试多个可能的路径
  const possiblePaths = [
    // 标准 extraResources 路径
    {
      pythonExe: path.join(process.resourcesPath, 'python_env', 'Scripts', 'python.exe'),
      script: path.join(process.resourcesPath, 'detect_game.py'),
      envDir: path.join(process.resourcesPath, 'python_env')
    },
    // 便携版可能路径
    {
      pythonExe: path.join(path.dirname(process.execPath), 'python_env', 'Scripts', 'python.exe'),
      script: path.join(path.dirname(process.execPath), 'detect_game.py'),
      envDir: path.join(path.dirname(process.execPath), 'python_env')
    },
    // 备用路径
    {
      pythonExe: path.join(process.resourcesPath, '..', 'python_env', 'Scripts', 'python.exe'),
      script: path.join(process.resourcesPath, '..', 'detect_game.py'),
      envDir: path.join(process.resourcesPath, '..', 'python_env')
    }
  ];

  // 返回第一个存在的路径
  for (const pathConfig of possiblePaths) {
    if (fs.existsSync(pathConfig.pythonExe) && fs.existsSync(pathConfig.script)) {
      console.log('找到有效路径:', pathConfig);
      return pathConfig;
    }
  }

  // 如果没有找到，返回第一个配置（用于错误信息）
  return possiblePaths[0];
}

// 停止日志监控
function stopLogMonitoring() {
  if (logWatcher) {
    logWatcher.close()
    logWatcher = null
  }
}

// 创建窗口
function createWindow() {
  try {
    console.log('开始创建窗口...')
    Menu.setApplicationMenu(null)

    // 窗口配置
    win = new BrowserWindow({
      width: 400,
      height: 600,
      resizable: false,
      alwaysOnTop: true,
      frame: false,
      transparent: false,
      backgroundColor: '#f5f5f5',
      paintWhenInitiallyHidden: false,
      webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
        enableRemoteModule: true,
        devTools: false,
        backgroundThrottling: false,
        webSecurity: false,
        allowRunningInsecureContent: true // 允许加载本地资源
      }
    })
    // win.webContents.openDevTools()
    // 窗口事件监听
    win.on('show', () => {
      console.log('窗口已显示')
    })

    win.on('error', (err) => {
      const errMsg = `窗口创建错误: ${err.message}`
      showErrorDialog('窗口错误', errMsg)
      showErrorPage(errMsg)
    })

    win.on('closed', () => {
      console.log('窗口已关闭')
      win = null
      stopLogMonitoring()
    })

    // 加载应用
    if (isDev) {
      console.log('开发模式: 加载开发服务器', process.env.WEBPACK_DEV_SERVER_URL);
      win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
        .then(() => {
          console.log('开发服务器加载成功');
          win.show(); // 确保加载成功后显示窗口
          win.webContents.openDevTools(); // 打开调试工具
        })
        .catch(err => {
          const errMsg = `开发模式加载失败: ${err.message}`;
          console.error(errMsg); // 强制打印错误
          showErrorDialog('加载失败', errMsg);
          showErrorPage(errMsg);
        });
    } else {
      console.log('生产模式: 加载打包文件')

      // 处理asar包内路径（index.html在asar根目录）
      const indexPath = app.isPackaged
        ? path.join(process.resourcesPath, 'app.asar', 'index.html')  // 打包后：asar根目录
        : path.join(__dirname, 'index.html');  // 开发模式：根据实际位置调整

      console.log('index.html路径:', indexPath)

      // 检查文件是否存在
      if (!fs.existsSync(indexPath)) {
        // 列出asar根目录下的所有文件（辅助调试）
        const asarRoot = app.isPackaged ? path.join(process.resourcesPath, 'app.asar') : __dirname;
        const rootFiles = fs.existsSync(asarRoot) ? fs.readdirSync(asarRoot) : [];
        const errMsg = `未找到index.html，asar根目录内容: ${JSON.stringify(rootFiles)}`;
        showErrorDialog('文件缺失', errMsg);
        showErrorPage(errMsg);
        return;
      }

      // 加载本地文件
      const fileUrl = new URL(`file://${indexPath}`).href;
      console.log('加载URL:', fileUrl);

      win.loadURL(fileUrl)
        .then(() => {
          console.log('页面加载成功');
          win.show();
        })
        .catch(err => {
          const errMsg = `页面加载失败: ${err.message}`;
          showErrorDialog('加载失败', errMsg);
          showErrorPage(errMsg);
        });
    }

    // 渲染进程事件监听
    win.webContents.on('did-finish-load', () => {
      console.log('页面加载完成')
      win.webContents.send('app-ready')

      // 注入调试信息
      win.webContents.executeJavaScript(`
        console.log('渲染进程就绪，当前URL:', window.location.href);
        const checkResources = () => {
          const resources = ['css', 'js'];
          resources.forEach(type => {
            const elements = document.querySelectorAll(
              type === 'css' ? 'link[rel="stylesheet"]' : 'script'
            );
            console.log(\`\${type}资源数量:\`, elements.length);
            elements.forEach((el, i) => {
              const url = el.href || el.src;
              console.log(\`\${type}[\${i}]: \${url}\`);
              
              // 检查资源是否可访问
              if (type === 'js') {
                fetch(url).catch(err => console.error(\`\${type}加载失败:\`, err));
              }
            });
          });
        };
        checkResources();
      `).catch(err => console.error('注入调试信息失败:', err))
    })

    // 资源加载失败监听
    win.webContents.on('did-fail-provisional-load', (event, errorCode, errorDescription, validatedURL) => {
      const errMsg = `资源加载失败[${errorCode}]: ${errorDescription}，URL: ${validatedURL}`
      console.error(errMsg)
      logError('资源加载失败', errMsg)
    })

    // 渲染进程错误监听
    win.webContents.on('uncaught-exception', (event, error) => {
      const errMsg = `渲染进程异常: ${error.message}`
      showErrorDialog('渲染进程错误', errMsg)
      logError('渲染进程异常', error)
    })

  } catch (error) {
    const errMsg = `创建窗口失败: ${error.message}`
    showErrorDialog('启动失败', errMsg)
    logError('创建窗口失败', error)
    // 失败后退出应用，避免僵尸进程
    setTimeout(() => app.quit(), 2000)
  }
}

// IPC事件处理
ipcMain.handle('retry-detect-game', async () => {
  return await autoDetectGameWindow()
})

ipcMain.handle('detect-game', async () => {
  console.log('接收到detect-game请求')
  return await autoDetectGameWindow()
})

ipcMain.on('window-minimize', () => {
  if (win && !win.isDestroyed()) {
    win.minimize()
  }
})

ipcMain.on('window-close', () => {
  console.log('接收到窗口关闭事件')
  if (win && !win.isDestroyed()) {
    win.destroy()
  }
})

ipcMain.handle('get-window-size', (event) => {
  const window = BrowserWindow.fromWebContents(event.sender)
  if (window) {
    const [width, height] = window.getSize()
    return { width, height }
  }
  return { width: 400, height: 600 }
})

ipcMain.on('set-window-size', (event, width, height) => {
  const window = BrowserWindow.fromWebContents(event.sender)
  if (window) {
    window.setResizable(true)
    window.setSize(width, height)
    window.center()
    window.setResizable(false)
  }
})

// 日志监控相关
ipcMain.on('set-log-path', (event, path) => {
  logPath = path
  lastPosition = 0
  try {
    if (fs.existsSync(logPath)) {
      const stats = fs.statSync(logPath)
      lastPosition = stats.size
    }
  } catch (e) {
    const errMsg = `获取日志信息失败: ${e.message}`
    console.error(errMsg)
    if (win && !win.isDestroyed()) {
      win.webContents.send('log-error', errMsg)
    }
  }
})

ipcMain.on('start-monitoring', () => {
  stopLogMonitoring()

  if (!logPath || !fs.existsSync(logPath)) {
    const errMsg = '日志路径不存在或未设置'
    if (win && !win.isDestroyed()) {
      win.webContents.send('log-error', errMsg)
    }
    return
  }

  logWatcher = fs.watch(logPath, (eventType) => {
    if (eventType !== 'change' || !win || win.isDestroyed()) return

    try {
      const stats = fs.statSync(logPath)
      if (stats.size < lastPosition) lastPosition = 0

      if (stats.size > lastPosition) {
        const fd = fs.openSync(logPath, 'r')
        const buffer = Buffer.alloc(stats.size - lastPosition)
        fs.readSync(fd, buffer, 0, buffer.length, lastPosition)
        fs.closeSync(fd)
        lastPosition = stats.size
        win.webContents.send('log-content', buffer.toString('utf8'))
      }
    } catch (e) {
      const errMsg = `读取日志失败: ${e.message}`
      console.error(errMsg)
      if (win && !win.isDestroyed()) {
        win.webContents.send('log-error', errMsg)
      }
    }
  })

  if (win && !win.isDestroyed()) {
    win.webContents.send('monitoring-status', true)
  }
})

ipcMain.on('stop-monitoring', () => {
  stopLogMonitoring()
  if (win && !win.isDestroyed()) {
    win.webContents.send('monitoring-status', false)
  }
})

// 文件操作相关
ipcMain.handle('file:mkdir', async (event, dirPath) => {
  try {
    await fs.ensureDir(dirPath)
    return { success: true }
  } catch (error) {
    return { success: false, error: error.message }
  }
})

ipcMain.handle('file:read', async (event, filePath) => {
  try {
    return await fs.readFile(filePath, 'utf-8')
  } catch (err) {
    console.error('读取文件失败:', err)
    return null
  }
})

ipcMain.handle('file:write', async (event, filePath, data) => {
  try {
    await fs.writeFile(filePath, data, 'utf-8')
    return true
  } catch (err) {
    console.error('写入文件失败:', err)
    return false
  }
})

ipcMain.handle('file:exists', async (event, filePath) => {
  return await fs.pathExists(filePath)
})

ipcMain.handle('file:write-price-table', async (event, filePath, content) => {
  try {
    const dir = path.dirname(filePath)
    await fs.ensureDir(dir)
    await fs.writeFile(filePath, content, 'utf8')
    console.log('价格表保存成功:', filePath)
    return { success: true }
  } catch (error) {
    console.error('价格表写入失败:', error)
    return { success: false, error: error.message }
  }
})

// 应用生命周期管理
app.whenReady().then(() => {
  console.log('应用准备就绪，创建窗口')
  createWindow()

  // 窗口全部关闭后重新创建（macOS）
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  console.log('所有窗口已关闭')
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('will-quit', () => {
  console.log('应用即将退出')
  stopLogMonitoring()
})

// 全局错误处理
process.on('uncaughtException', (error) => {
  const errMsg = `未捕获异常: ${error.message}`
  showErrorDialog('严重错误', errMsg)
  logError('未捕获异常', error)
  // 发生严重错误后退出应用
  setTimeout(() => app.quit(), 3000)
})

process.on('unhandledRejection', (reason, promise) => {
  const errMsg = `未处理的Promise拒绝: ${(reason && reason.message) || reason}`
  showErrorDialog('Promise错误', errMsg)
  logError('未处理的Promise拒绝', reason)
})